﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.LIB.YJKControls;
using YJKArchUtils.ControlUtility;

namespace YJKRevitBeam
{
	public partial class BeamsCreateForm : System.Windows.Forms.Form
	{
		public int mode
		{
			get
			{
				return this.m_mode;
			}
		}

		public bool clickModeBtn
		{
			get
			{
				return this.m_clickModeBtn;
			}
			set
			{
				this.m_clickModeBtn = value;
			}
		}

		public BeamsCreateForm(ExternalCommandData cmdData, BeamFormData dlgData)
		{
			this.InitializeComponent();
			this.m_cmdData = cmdData;
			this.m_dlgData = dlgData;
			List<Element> levels = this.m_dlgData.Levels;
			this.clbLevels.Items.Clear();
			Level genLevel = this.m_cmdData.Application.ActiveUIDocument.ActiveView.GenLevel;
			int num = -1;
			for (int i = 0; i < levels.Count; i++)
			{
				Element element = levels[i];
				Level level = element as Level;
				if (level != null && genLevel.Id.IntegerValue == level.Id.IntegerValue)
				{
					num = i;
				}
				this.clbLevels.Items.Add(element.Name);
			}
			if (-1 != num)
			{
				this.clbLevels.SetItemChecked(num, true);
			}
			foreach (Element element2 in this.m_dlgData.BeamSymbols)
			{
				FamilySymbol familySymbol = element2 as FamilySymbol;
				Bitmap previewImage = familySymbol.GetPreviewImage(new Size(36, 36));
				Family family = familySymbol.Family;
                //this.comboList1.Add(family.Name, familySymbol.Name, previewImage);
                //this.comboList2.Add(family.Name, familySymbol.Name, previewImage);
			}
		}

		private void BeamsCreateForm_Load(object sender, EventArgs e)
		{
            //this.comboList1.OnComboboxSelectionChanged += this.comboList_SelectChanged;
            //this.comboList2.OnComboboxSelectionChanged += this.comboList_SelectChanged;
			base.StartPosition = FormStartPosition.Manual;
			if (!this.ReadData())
			{
				base.Location = RevitVersionFuncs.GetRevitTopLeftPoint(this.m_cmdData);
				this.m_mode = 0;
                //this.comboList1.SetSelectedIndex(1);
                //this.comboList2.SetSelectedIndex(1);
				this.chkSegment.Checked = false;
				this.tbOffsetEdgeZ.Text = "0";
				this.tbOffsetEdgeXY.Text = "0";
				this.tbOffsetInnerZ.Text = "0";
				this.tbOffsetInnerXY.Text = "0";
			}
			this.SetFormByMode();
		}

		private void comboList_SelectChanged(object sender, MyControlEventArgs args)
		{
			string name = args.Name;
			FamilySymbol familySymbol = this.ExistTypeName(name);
            //ComboList comboList = sender as ComboList;
            //if (this.comboList1 == comboList)
            //{
            //    this.lbFamilyNameEdge.Text = familySymbol.Family.Name;
            //    return;
            //}
            //if (this.comboList2 == comboList)
            //{
            //    this.lbFamilyNameInner.Text = familySymbol.Family.Name;
            //}
		}

		private void SetFormByMode()
		{
			if (this.m_mode == 0)
			{
				this.chkSegment.Visible = false;
				this.groupBox2.Visible = false;
				this.lbFamilyNameInner.Visible = false;
				this.elementHostInner.Visible = false;
				this.lbOffsetInnerZ.Visible = false;
				this.tbOffsetInnerZ.Visible = false;
				this.lbOffsetInnerXY.Visible = false;
				this.tbOffsetInnerXY.Visible = false;
				return;
			}
			if (1 == this.m_mode)
			{
				this.chkSegment.Visible = true;
				this.groupBox2.Visible = false;
				this.lbFamilyNameInner.Visible = false;
				this.elementHostInner.Visible = false;
				this.lbOffsetInnerZ.Visible = false;
				this.tbOffsetInnerZ.Visible = false;
				this.lbOffsetInnerXY.Visible = false;
				this.tbOffsetInnerXY.Visible = false;
				return;
			}
			if (2 == this.m_mode)
			{
				this.chkSegment.Visible = false;
				this.groupBox2.Visible = true;
				this.lbFamilyNameInner.Visible = true;
				this.elementHostInner.Visible = true;
				this.lbOffsetInnerZ.Visible = true;
				this.tbOffsetInnerZ.Visible = true;
				this.lbOffsetInnerXY.Visible = true;
				this.tbOffsetInnerXY.Visible = true;
			}
		}

		private void btnSelAll_Click(object sender, EventArgs e)
		{
			for (int i = 0; i < this.clbLevels.Items.Count; i++)
			{
				this.clbLevels.SetItemChecked(i, true);
			}
		}

		private void btnSelReverse_Click(object sender, EventArgs e)
		{
			for (int i = 0; i < this.clbLevels.Items.Count; i++)
			{
				this.clbLevels.SetItemChecked(i, !this.clbLevels.GetItemChecked(i));
			}
		}

		private void radioButton1_Click(object sender, EventArgs e)
		{
			this.m_mode = 0;
			this.SetFormByMode();
			this.m_clickModeBtn = true;
			this.KeyEsc();
		}

		private void radioButton2_Click(object sender, EventArgs e)
		{
			this.m_mode = 1;
			this.SetFormByMode();
			this.m_clickModeBtn = true;
			this.KeyEsc();
		}

		private void radioButton3_Click(object sender, EventArgs e)
		{
			this.m_mode = 2;
			this.SetFormByMode();
			this.m_clickModeBtn = true;
			this.KeyEsc();
		}

		[DllImport("user32.dll")]
		public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		private void KeyEsc()
		{
			int bVk = 27;
			int dwFlags = 0;
			int dwFlags2 = 2;
			int wMsg = 7;
			BeamsCreateForm.SendMessage(CmdBeamsCreate._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			BeamsCreateForm.keybd_event((byte)bVk, 0, dwFlags, 0);
			BeamsCreateForm.keybd_event((byte)bVk, 0, dwFlags2, 0);
		}

		public BeamData GetDlgBeamData()
		{
			BeamData beamData = default(BeamData);
			List<Element> levels = this.m_dlgData.Levels;
			beamData.levels = new List<Level>();
			foreach (int index in this.GetSelLevelIndex())
			{
				Level level = levels[index] as Level;
				if (level != null)
				{
					beamData.levels.Add(level);
				}
			}


            Document doc = this.m_cmdData.Application.ActiveUIDocument.Document;


            foreach (Element element in ElementFiltering.FindSpecialElements(doc, typeof(FamilySymbol), BuiltInCategory.OST_StructuralFraming))
            {
                FamilySymbol familySymbol = element as FamilySymbol;
                if (familySymbol != null)
                {
                    string sss = familySymbol.Name;
                    beamData.beamEdge = familySymbol;
                    beamData.beamInner = familySymbol;
                    break;
                }
            }


            


            //FamilySymbol familySymbol = this.ExistTypeName(this.comboList1.GetCurrentText());
            //if (familySymbol != null)
            //{
            //    beamData.beamEdge = familySymbol;
            //}
            //FamilySymbol familySymbol2 = this.ExistTypeName(this.comboList2.GetCurrentText());
            //if (familySymbol2 != null)
            //{
            //    beamData.beamInner = familySymbol2;
            //}
			beamData.isSegment = this.chkSegment.Checked;
			try
			{
				beamData.offsetEdgeZ = double.Parse(this.tbOffsetEdgeZ.Text);
				beamData.offsetEdgeXY = double.Parse(this.tbOffsetEdgeXY.Text);
				beamData.offsetInnerZ = double.Parse(this.tbOffsetInnerZ.Text);
				beamData.offsetInnerXY = double.Parse(this.tbOffsetInnerXY.Text);
			}
			catch
			{
				TaskDialog.Show("盈建科", "请输入合法字符。");
				this.tbOffsetEdgeZ.Text = this.m_offsetEdgeZ;
				this.tbOffsetEdgeXY.Text = this.m_offsetEdgeXY;
				this.tbOffsetInnerZ.Text = this.m_offsetInnerZ;
				this.tbOffsetInnerXY.Text = this.m_offsetInnerXY;
				throw;
			}
			return beamData;
		}

		public List<int> GetSelLevelIndex()
		{
			List<int> list = new List<int>();
			for (int i = 0; i < this.clbLevels.Items.Count; i++)
			{
				if (this.clbLevels.GetItemChecked(i))
				{
					list.Add(i);
				}
			}
			return list;
		}

		private void BeamsCreateForm_MouseLeave(object sender, EventArgs e)
		{
			try
			{
				double.Parse(this.tbOffsetEdgeZ.Text);
				double.Parse(this.tbOffsetEdgeXY.Text);
				double.Parse(this.tbOffsetInnerZ.Text);
				double.Parse(this.tbOffsetInnerXY.Text);
			}
			catch
			{
				TaskDialog.Show("盈建科", "请输入合法字符。");
				this.tbOffsetEdgeZ.Text = this.m_offsetEdgeZ;
				this.tbOffsetEdgeXY.Text = this.m_offsetEdgeXY;
				this.tbOffsetInnerZ.Text = this.m_offsetInnerZ;
				this.tbOffsetInnerXY.Text = this.m_offsetInnerXY;
			}
			if (!base.ClientRectangle.Contains(base.PointToClient(Cursor.Position)))
			{
				int wMsg = 7;
				BeamsCreateForm.SendMessage(CmdBeamsCreate._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
				return;
			}
			base.Focus();
		}

		private void BeamsCreateForm_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
			{
				base.Close();
			}
		}

		private void BeamsCreateForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.SaveData();
		}

		private void BeamsCreateForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			this.KeyEsc();
		}

		private void SaveData()
		{
			FileStream fileStream = new FileStream(Path.GetTempPath() + "GridToBeam.dat", FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			streamWriter.WriteLine(base.Location.X);
			streamWriter.WriteLine(base.Location.Y);
			streamWriter.WriteLine(this.m_mode);
			streamWriter.WriteLine(this.chkSegment.Checked);
            //streamWriter.WriteLine(this.comboList1.GetCurrentText());
			streamWriter.WriteLine(this.tbOffsetEdgeZ.Text);
			streamWriter.WriteLine(this.tbOffsetEdgeXY.Text);
            //streamWriter.WriteLine(this.comboList2.GetCurrentText());
			streamWriter.WriteLine(this.tbOffsetInnerZ.Text);
			streamWriter.WriteLine(this.tbOffsetInnerXY.Text);
			streamWriter.Flush();
			streamWriter.Close();
			fileStream.Close();
		}

		private bool ReadData()
		{
			string path = Path.GetTempPath() + "GridToBeam.dat";
			if (!File.Exists(path))
			{
				return false;
			}
			FileStream fileStream = new FileStream(path, FileMode.Open);
			StreamReader streamReader = new StreamReader(fileStream);
			streamReader.BaseStream.Seek(0L, SeekOrigin.Begin);
			try
			{
				int x = Convert.ToInt32(streamReader.ReadLine());
				int y = Convert.ToInt32(streamReader.ReadLine());
				base.Location = new System.Drawing.Point(x, y);
				string text = streamReader.ReadLine();
				this.m_mode = int.Parse(text);
				text = streamReader.ReadLine();
				this.chkSegment.Checked = bool.Parse(text);
				string currentText = streamReader.ReadLine();
                //this.comboList1.SetCurrentText(currentText);
				this.tbOffsetEdgeZ.Text = streamReader.ReadLine();
				this.tbOffsetEdgeXY.Text = streamReader.ReadLine();
				string currentText2 = streamReader.ReadLine();
                //this.comboList2.SetCurrentText(currentText2);
				this.tbOffsetInnerZ.Text = streamReader.ReadLine();
				this.tbOffsetInnerXY.Text = streamReader.ReadLine();


                if (this.tbOffsetInnerZ.Text == "")
                {
                    this.tbOffsetInnerZ.Text = "0";
                }

                if (this.tbOffsetInnerXY.Text == "")
                {
                    this.tbOffsetInnerXY.Text = "0";
                }
			}
			catch
			{
				return false;
			}
			finally
			{
				streamReader.Close();
				fileStream.Close();
			}
			if (this.m_mode == 0)
			{
				this.radioButton1.Checked = true;
				this.radioButton2.Checked = false;
				this.radioButton3.Checked = false;
			}
			else if (1 == this.m_mode)
			{
				this.radioButton2.Checked = true;
				this.radioButton1.Checked = false;
				this.radioButton3.Checked = false;
			}
			else if (2 == this.m_mode)
			{
				this.radioButton3.Checked = true;
				this.radioButton1.Checked = false;
				this.radioButton2.Checked = false;
			}
			return true;
		}

		private FamilySymbol ExistTypeName(string typeName)
		{
			new List<string>();
			foreach (Element element in this.m_dlgData.BeamSymbols)
			{
				FamilySymbol familySymbol = element as FamilySymbol;
				if (familySymbol.Name == typeName)
				{
					return familySymbol;
				}
			}
			return null;
		}

		private void tbOffsetEdgeZ_TextChanged(object sender, EventArgs e)
		{
			if (1 == this.tbOffsetEdgeZ.Text.Length && this.tbOffsetEdgeZ.Text.CompareTo("-") == 0)
			{
				return;
			}
			try
			{
				double.Parse(this.tbOffsetEdgeZ.Text);
			}
			catch (FormatException)
			{
				TaskDialog.Show("盈建科", "请输入合法字符。");
				this.tbOffsetEdgeZ.Text = this.m_offsetEdgeZ;
			}
			this.m_offsetEdgeZ = this.tbOffsetEdgeZ.Text;
		}

		private void tbOffsetEdgeXY_TextChanged(object sender, EventArgs e)
		{
			if (1 == this.tbOffsetEdgeXY.Text.Length && this.tbOffsetEdgeXY.Text.CompareTo("-") == 0)
			{
				return;
			}
			try
			{
				double.Parse(this.tbOffsetEdgeXY.Text);
			}
			catch (FormatException)
			{
				TaskDialog.Show("盈建科", "请输入合法字符。");
				this.tbOffsetEdgeXY.Text = this.m_offsetEdgeXY;
			}
			this.m_offsetEdgeXY = this.tbOffsetEdgeXY.Text;
		}

		private void tbOffsetInnerZ_TextChanged(object sender, EventArgs e)
		{
			if (1 == this.tbOffsetInnerZ.Text.Length && this.tbOffsetInnerZ.Text.CompareTo("-") == 0)
			{
				return;
			}
			try
			{
				double.Parse(this.tbOffsetInnerZ.Text);
			}
			catch (FormatException)
			{
				TaskDialog.Show("盈建科", "请输入合法字符。");
				this.tbOffsetInnerZ.Text = this.m_offsetInnerZ;
			}
			this.m_offsetInnerZ = this.tbOffsetInnerZ.Text;
		}

		private void tbOffsetInnerXY_TextChanged(object sender, EventArgs e)
		{
			if (1 == this.tbOffsetInnerXY.Text.Length && this.tbOffsetInnerXY.Text.CompareTo("-") == 0)
			{
				return;
			}
			try
			{
				double.Parse(this.tbOffsetInnerXY.Text);
			}
			catch (FormatException)
			{
				TaskDialog.Show("盈建科", "请输入合法字符。");
				this.tbOffsetInnerXY.Text = this.m_offsetInnerXY;
			}
			this.m_offsetInnerXY = this.tbOffsetInnerXY.Text;
		}

		private void tbOffsetEdgeZ_KeyPress(object sender, KeyPressEventArgs e)
		{
			if ('-' == e.KeyChar || '.' == e.KeyChar)
			{
				return;
			}
			if (e.KeyChar != '\b' && (e.KeyChar < '0' || e.KeyChar > '9'))
			{
				e.Handled = true;
			}
		}

		private void tbOffsetEdgeXY_KeyPress(object sender, KeyPressEventArgs e)
		{
			if ('-' == e.KeyChar || '.' == e.KeyChar)
			{
				return;
			}
			if (e.KeyChar != '\b' && (e.KeyChar < '0' || e.KeyChar > '9'))
			{
				e.Handled = true;
			}
		}

		private void tbOffsetInnerZ_KeyPress(object sender, KeyPressEventArgs e)
		{
			if ('-' == e.KeyChar || '.' == e.KeyChar)
			{
				return;
			}
			if (e.KeyChar != '\b' && (e.KeyChar < '0' || e.KeyChar > '9'))
			{
				e.Handled = true;
			}
		}

		private void tbOffsetInnerXY_KeyPress(object sender, KeyPressEventArgs e)
		{
			if ('-' == e.KeyChar || '.' == e.KeyChar)
			{
				return;
			}
			if (e.KeyChar != '\b' && (e.KeyChar < '0' || e.KeyChar > '9'))
			{
				e.Handled = true;
			}
		}

		private ExternalCommandData m_cmdData;

		private BeamFormData m_dlgData;

		private int m_mode;

		private bool m_clickModeBtn;

		private string m_offsetEdgeZ = "0";

		private string m_offsetEdgeXY = "0";

		private string m_offsetInnerZ = "0";

		private string m_offsetInnerXY = "0";
	}
}
